<template>
  <el-row>
    <el-col :span="4">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree :data="treeData" :option="treeOption" @node-click="nodeClick"/>
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="20">
      <el-tabs type="border-card" @tab-click="tabHandleClick">

        <el-tab-pane label="图表">
          <basic-container>
            <avue-form v-model="excelForm" :option="excelOption" @error="error"
                       @submit="searchClick">
            </avue-form>

            <el-button icon="el-icon-plus"
                       size="small"
                       type="success"
                       @click="$refs.crud.rowAdd()">新增
            </el-button>
            <!-- <el-button type="warning"
                       icon="el-icon-delete"
                       size="small"
                       >清空课表</el-button> -->
            <div id="coursesTable" @contextmenu.prevent="onContextmenu"></div>
          </basic-container>
        </el-tab-pane>
        <el-tab-pane label="列表">
          <basic-container>
            <avue-crud ref="crud"
                       v-model="form"
                       :before-open="beforeOpen"
                       :data="data"
                       :option="option"
                       :page="page"
                       :permission="permissionList"
                       :table-loading="loading"
                       @row-update="rowUpdate"
                       @row-save="rowSave"
                       @row-del="rowDel"
                       @search-change="searchChange"
                       @search-reset="searchReset"
                       @selection-change="selectionChange"
                       @current-change="currentChange"
                       @size-change="sizeChange"
                       @on-load="onLoad"
            >
              <template slot="menuLeft">
                <el-button v-if="permission.bjkcsort_delete"
                           icon="el-icon-delete"
                           plain
                           size="small"
                           type="danger"
                           @click="handleDelete">删 除
                </el-button>
              </template>
            </avue-crud>


          </basic-container>
        </el-tab-pane>
      </el-tabs>


    </el-col>
  </el-row>

</template>

<script>
import {
  add,
  getBjTree,
  getCourseSelect,
  getKebiao,
  getList,
  grade,
  gradeDic,
  remove,
  schoolClass,
  update
} from "@/api/service/bjkcsort";
import {mapGetters} from "vuex";

import Timetables from 'timetables';
import {contrastTime} from "@/util/validate";

var timetables = [
  ['', '', '', '', '', '', '', '', '', '', '', ''],
  ['', '', '', '', '', '', '', '', '', '', '', ''],
  ['', '', '', '', '', '', '', '', '', '', '', ''],
  ['', '', '', '', '', '', '', '', '', '', '', ''],
  ['', '', '', '', '', '', '', '', '', '', '', ''],
  ['', '', '', '', '', '', '', '', '', '', '', ''],
  ['', '', '', '', '', '', '', '', '', '', '', ''],
];


const highlightWeek = new Date().getDay();


export default {
  data() {
    return {
      tt: false,
      treeBj: '0',
      treeData: [],
      excelForm: {isAnswer: '0'},
      treeOption: {
        nodeKey: 'id',
        lazy: false,
        addBtn: false,
        menu: false,
        size: 'small',
        defaultExpandAll: true,
        props: {
          labelText: '标题',
          label: 'title',
          value: 'id',
          children: 'children'
        }
      },
      type: {},
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      currentClickNode: [],
      kbIndex: [[]],
      selectionList: [],
      excelOption: {
        submitBtn: true,
        emptyBtn: true,
        submitText: '搜索',
        column: [
          {
            label: "学校名称",
            prop: "schoolId",
            search: true,
            hide: true,
            // rules: [{
            //   required: true,
            //   message: "请输入学校名称",
            //   trigger: "blur"
            // }],
            type: "tree",
            dicUrl: "/api/PcPublicService/GetSchoolTreeSelect",
            cascader: ['jdId'],
            props: {
              label: "xxName",
              value: "id"
            },
            change: ({value}) => {
              this.schoolTypeChange(value);
            }
          },
          {
            label: "所属阶段",
            prop: "jdId",
            search: true,
            // rules: [{
            //   required: true,
            //   message: "请选择所属阶段",
            //   trigger: "blur"
            // }],
            hide: true,
            type: "select",
            dicUrl: "/api/ManageClassCoursePlan/GetSchoolStageSelect",
            cascader: ['njId'],
            props: {
              label: "title",
              value: "id"
            },
            change: ({value}) => {
              this.jdIdTypeChange(value);
            }
          },
          // {
          //   label: "学期",
          //   prop: "xqId",
          //   search: true,
          //   rules: [{
          //     required: true,
          //     message: "请选择学期",
          //     trigger: "blur"
          //   }],
          //   hide: true,
          //   type: "select",
          //   dicUrl: "/api/ManageClassCoursePlan/GetSchoolSemesterSelect?schoolId={{key}}",
          //   props: {
          //     label: "xqName",
          //     value: "id"
          //   },
          // },
          {
            label: "年级",
            prop: "njId",
            type: "select",
            search: true,
            overHidden: true,
            hide: true,
            // rules: [{
            //   required: true,
            //   message: "请选择年级",
            //   trigger: "blur"
            // }],
            props: {
              label: "title",
              value: "id"
            },
            cascader: ['bjId'],
            dicData: [],
            change: ({value}) => {
              this.njIdTypeChange(value);
            }
          },
          {
            label: "班级",
            prop: "bjId",
            type: "select",
            search: true,
            overHidden: true,
            hide: true,
            // rules: [{
            //   required: true,
            //   message: "请选择班级",
            //   trigger: "blur"
            // }],
            cascader: ['bjKcId'],
            // hide: true,
            props: {
              label: "bjName",
              value: "id"
            },
            dicData: [],
          },
        ]
      },
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        // menuType: 'menu',
        // menuBtnTitle: '更多操作',
        column: [
          {
            label: "主键",
            prop: "id",
            rules: [{
              required: true,
              message: "请输入主键",
              trigger: "blur"
            }],
            hide: true,
            display: false
          },
          {
            label: "学校名称",
            prop: "schoolId",
            search: true,
            hide: true,
            rules: [{
              required: true,
              message: "请输入学校名称",
              trigger: "blur"
            }],
            type: "tree",
            dicUrl: "/api/PcPublicService/GetSchoolTreeSelect",
            cascader: ['jdId', 'xqId'],
            props: {
              label: "xxName",
              value: "id"
            },
            change: ({value}) => {
              this.schoolTypeChange(value);
            }
          },
          {
            label: "所属阶段",
            prop: "jdId",
            search: true,
            rules: [{
              required: true,
              message: "请选择所属阶段",
              trigger: "blur"
            }],
            hide: true,
            type: "select",
            dicUrl: "/api/ManageClassCoursePlan/GetSchoolStageSelect",
            cascader: ['njId'],
            props: {
              label: "title",
              value: "id"
            },
            change: ({value}) => {
              this.jdIdTypeChange(value);
            }
          },
          {
            label: "学期",
            prop: "xqId",
            search: true,
            rules: [{
              required: true,
              message: "请选择学期",
              trigger: "blur"
            }],
            hide: true,
            type: "select",
            dicUrl: "/api/ManageClassCoursePlan/GetSchoolSemesterSelect?schoolId={{key}}",
            props: {
              label: "xqName",
              value: "id"
            },
          },
          {
            label: "年级",
            prop: "njId",
            type: "select",
            search: true,
            overHidden: true,
            hide: true,
            rules: [{
              required: true,
              message: "请选择年级",
              trigger: "blur"
            }],
            props: {
              label: "title",
              value: "id"
            },
            cascader: ['bjId'],
            dicData: [],
            change: ({value}) => {
              this.njIdTypeChange(value);
            }
          },
          {
            label: "班级",
            prop: "bjId",
            type: "select",
            search: true,
            overHidden: true,
            hide: true,
            rules: [{
              required: true,
              message: "请选择班级",
              trigger: "blur"
            }],
            cascader: ['bjKcId'],
            // hide: true,
            props: {
              label: "bjName",
              value: "id"
            },
            dicData: [],
          },
          {
            label: "班级课程",
            prop: "kcName",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            rules: [{
              required: true,
              message: "请输入班级课程",
              trigger: "blur"
            }],

          },
          {
            label: "班级课程",
            prop: "bjKcId",
            type: "select",
            overHidden: true,
            search: false,
            rules: [{
              required: true,
              message: "请选择班级课程",
              trigger: "blur"
            }],
            hide: true,
            dicUrl: "/api/ManageClassCoursePlan/GetClassCourseSelect?bjId={{key}}",
            props: {
              label: "kcName",
              value: "id"
            },
            // dataType: "string",
          },
          {
            label: "课程天",
            prop: "kcZhou",
            rules: [{
              required: true,
              message: "请输入课程天",
              trigger: "blur"
            }],
            type: "select",
            dicData: [
              {
                label: "周一",
                value: 1
              },
              {
                label: "周二",
                value: 2
              },
              {
                label: "周三",
                value: 3
              },
              {
                label: "周四",
                value: 4
              },
              {
                label: "周五",
                value: 5
              },
              {
                label: "周六",
                value: 6
              },
              {
                label: "周日",
                value: 7
              },
            ],
            dataType: 'number',
          },
          {
            label: "课程节",
            prop: "kcJie",
            rules: [{
              required: true,
              message: "请输入课程节",
              trigger: "blur"
            }],
            type: "select",
            dicData: [
              {
                label: "上午第一节",
                value: 1
              },
              {
                label: "上午第二节",
                value: 2
              },
              {
                label: "上午第三节",
                value: 3
              },
              {
                label: "上午第四节",
                value: 4
              },
              {
                label: "下午第一节",
                value: 5
              },
              {
                label: "下午第二节",
                value: 6
              },
              {
                label: "下午第三节",
                value: 7
              },
              {
                label: "下午第四节",
                value: 8
              },
              {
                label: "晚上第一节",
                value: 9
              },
              {
                label: "晚上第二节",
                value: 10
              },
              {
                label: "晚上第三节",
                value: 11
              },
              {
                label: "晚上第四节",
                value: 12
              },
            ],
            dataType: 'number',
          },
          {
            label: "连续节数",
            prop: "kcJieNum",
            rules: [{
              required: true,
              message: "请输入连续节数",
              trigger: "blur"
            }],
            disabled: true,
            type: "number",
            value: 1,
          },
          {
            label: "开始时间",
            prop: "startTime",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入开始时间",
              trigger: "blur"
            }]
          },
          {
            label: "结束时间",
            prop: "endTime",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入结束时间",
              trigger: "blur"
            }]
          },
        ]
      },
      data: [],
      schoolId: '',
      labelName: '图表'
    };
  },
  computed: {
    ...mapGetters(["permission", "JSuserInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.bjkcsort_add, false),
        viewBtn: this.vaildData(this.permission.bjkcsort_view, false),
        delBtn: this.vaildData(this.permission.bjkcsort_delete, false),
        editBtn: this.vaildData(this.permission.bjkcsort_edit, false)
      };
    },
    js_Id() {
      return this.JSuserInfo.js_Id
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
    getBjTree({}).then(res => {
      this.treeData = res.data.data;
    });
    this.initkb();
  },
  methods: {
    schoolTypeChange(v) {
      console.log(v)
      this.schoolId = v
      // 年级
      const school = this.findObject(this.option.column, "njId");
      school.dicData = [];
    },
    // 切换所属阶段
    jdIdTypeChange(v) {
      console.log('切换所属阶段', v)
      if (this.schoolId !== "" && this.schoolId !== null && this.schoolId !== undefined && v !== "" && v !== null && v !== undefined) {
        let params = {
          schoolId: this.schoolId,
          jdId: v
        }
        console.log('111111111111111111切换所属阶段')
        grade(params).then(res => {
          // const gradeData = this.findObject(this.option.column, "njId");
          const excelOptionData = this.findObject(this.excelOption.column, "njId");
          // gradeData.dicData = res.data.data;
          // excelOptionData.dicData = []
          // res.data.data.forEach((item,index)=>{
          //   Vue.set(excelOptionData.dicData, index, item)
          // })
          setTimeout(() => {
            excelOptionData.dicData = res.data.data;
          }, 300)

          // let newObj = Object.assign({}, excelOptionData.dicData , )
          console.log('excelOptionData', excelOptionData)
          console.log('excelOptionDataDicData', res.data.data)
        });
      }
    },
    njIdTypeChange(v) {
      if (v !== null && v !== '' && v !== undefined) {
        // let params = {
        //   njId: v,
        // }
        gradeDic({njId: v}).then(res => {
          schoolClass({njId: res.data.data.id}).then(res => {
            const calssData = this.findObject(this.option.column, "bjId");
            const excelOptionData = this.findObject(this.excelOption.column, "bjId");
            calssData.dicData = res.data.data;
            excelOptionData.dicData = res.data.data;
          })
        });
      }
    },
    onContextmenu(event) {
      if (this.currentClickNode.name != "") {
        // this.$contextmenu({
        //   items: [
        //     {
        //       label: "删除课程",
        //       icon: "el-icon-remove",
        //       onClick: () => {
        //         var kcJie = this.currentClickNode.index-1;
        //         var w = this.currentClickNode.week;
        //        var kcZhou = 0;
        //         if(w=="周一"){
        //           kcZhou = 0;
        //         }
        //         if(w=="周二"){
        //           kcZhou = 1;
        //         }
        //         if(w=="周三"){
        //           kcZhou = 2;
        //         }
        //         if(w=="周四"){
        //           kcZhou = 3;
        //         }
        //         if(w=="周五"){
        //           kcZhou = 4;
        //         }
        //         if(w=="周六"){
        //           kcZhou = 5;
        //         }
        //         if(w=="周日"){
        //           kcZhou = 6;
        //         }
        //         var id = this.kbIndex[kcZhou][kcJie];
        //         console.log(kcZhou+","+kcJie+","+id);
        //         this.rowDel({"id":id});
        //       }
        //     }
        //   ],
        //   event, // 鼠标事件信息
        //   customClass: "custom-class", // 自定义菜单 class
        //   zIndex: 3, // 菜单样式 z-index
        //   minWidth: 50 // 主菜单最小宽度
        // });
      } else {
        this.$contextmenu({
          items: [
            {
              label: "添加课程",
              icon: "el-icon-circle-plus",
              onClick: () => {
                this.form.kcJie = this.currentClickNode.index;
                var w = this.currentClickNode.week;
                if (w == "周一") {
                  this.form.kcZhou = 1;
                }
                if (w == "周二") {
                  this.form.kcZhou = 2;
                }
                if (w == "周三") {
                  this.form.kcZhou = 3;
                }
                if (w == "周四") {
                  this.form.kcZhou = 4;
                }
                if (w == "周五") {
                  this.form.kcZhou = 5;
                }
                if (w == "周六") {
                  this.form.kcZhou = 6;
                }
                if (w == "周日") {
                  this.form.kcZhou = 7;
                }
                this.$refs.crud.rowAdd();
              }
            }
          ],
          event, // 鼠标事件信息
          customClass: "custom-class", // 自定义菜单 class
          zIndex: 3, // 菜单样式 z-index
          minWidth: 50 // 主菜单最小宽度
        });
      }
      return false;
    },
    tabHandleClick(tab, event) {
      console.log(event, tab)
      this.labelName = tab.label
      if (tab.label == '图表') {
        this.initkb();
      } else {
        this.onLoad(this.page);
      }
    },
    nodeClick(data) {
      if (data.hasChildren) {
        this.treeBj = data.id;
        if (this.labelName === '图表') {
          this.initkb();
        } else {
          this.onLoad(this.page);
        }
      } else {
        this.data = []
      }

      // this.form.bjId =
    },
    initkb() {
      getKebiao({bjId: this.treeBj}).then(res => {
        timetables = [
          ['', '', '', '', '', '', '', '', '', '', '', ''],
          ['', '', '', '', '', '', '', '', '', '', '', ''],
          ['', '', '', '', '', '', '', '', '', '', '', ''],
          ['', '', '', '', '', '', '', '', '', '', '', ''],
          ['', '', '', '', '', '', '', '', '', '', '', ''],
          ['', '', '', '', '', '', '', '', '', '', '', ''],
          ['', '', '', '', '', '', '', '', '', '', '', ''],
        ];
        this.initKebiaoData(res.data.data);
      });
    },
    initKebiaoData(list) {
      this.kbIndex = [
        ['', '', '', '', '', '', '', '', '', '', '', ''],
        ['', '', '', '', '', '', '', '', '', '', '', ''],
        ['', '', '', '', '', '', '', '', '', '', '', ''],
        ['', '', '', '', '', '', '', '', '', '', '', ''],
        ['', '', '', '', '', '', '', '', '', '', '', ''],
        ['', '', '', '', '', '', '', '', '', '', '', ''],
        ['', '', '', '', '', '', '', '', '', '', '', ''],
      ];
      for (var i in list) {
        var kc = list[i];
        var z = Number(kc.kcZhou) - 1;
        var j = Number(kc.kcJie) - 1;
        var n = kc.kcJieNum;
        timetables[z][j] = kc.kcName;
        this.kbIndex[z][j] = kc.id;

        if (n > 1) {
          for (var ii = 1; ii < n; ii++) {
            j = j + 1;
            timetables[z][j] = kc.kcName;
            this.kbIndex[z][j] = kc.id;

          }
        }
      }
      var that = this;
      if (this.tt) {
        this.tt.setOption({
          timetables: timetables,
          highlightWeek: highlightWeek,
          merge: false,

          week: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          timetableType: [
            ['上午', 4],
            ['下午', 4],
            ['晚上', 4]

          ],
          gridOnClick: function (e) {
            that.currentClickNode = e;
          },
        })
      } else {
        console.log('highlightWeek', highlightWeek)
        this.tt = new Timetables({
          el: '#coursesTable',
          timetables: timetables,
          highlightWeek: highlightWeek,
          merge: false,
          week: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          timetableType: [
            ['上午', 4],
            ['下午', 4],
            ['晚上', 4]
          ],
          gridOnClick: function (e) {
            that.currentClickNode = e;
          },
        });
      }
    },

    rowSave(row, done, loading) {
      if (!contrastTime(row.startTime, row.endTime)) {
        this.$message({
          type: "warning",
          message: "开始时间不可大于结束时间!"
        });
        loading();
        return 0
      }
      row.id = row.id === '' ? '0' : row.id
      console.log(row)
      getCourseSelect({id: row.bjKcId}).then((res) => {
        row.kcId = res.data.data.kcId
        add(row).then(() => {
          done();
          if (this.labelName === '图表') {
            this.initkb();
          } else {
            this.onLoad(this.page);
          }
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      }, error => {
        window.console.log(error);
        loading();
      })
    },
    rowUpdate(row, index, done, loading) {
      if (!contrastTime(row.startTime, row.endTime)) {
        this.$message({
          type: "warning",
          message: "开始时间不可大于结束时间!"
        });
        loading();
        return 0
      }
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: row.id});
        })
        .then(() => {
          if (this.labelName === '图表') {
            this.initkb();
          } else {
            this.onLoad(this.page);
          }
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: this.ids});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit"].includes(type)) {
        // getDetail({id: this.form.id}).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    searchClick(form, done) {
      console.log(form)
      getList(1, 10, form).then(res => {
        done()
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });

    },
    onLoad(page, params = {}) {
      this.loading = true;
      // params.bjId = this.treeBj;

      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        // data.records.forEach(item => {
        //   // item.jdId = item.jdName
        //   // item.bjId = item.bjName
        //   item.bjKcId = item.kcName
        // })
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
      // this.initkb();
      // GradesByTeacher({AppUserId: this.js_Id}).then(res => {
      //   this.treeData = res.data.data;
      //   if (this.treeBj == "0") {
      //     this.treeBj = res.data.data[0].id
      //     this.onLoad(this.page);
      //     // this.initkb();
      //   }
      // });
    }
  }
};
</script>

<style>
#coursesTable {
  /*padding: 15px 10px;*/
  margin-top: 15px;
}

.Courses-head > div {
  text-align: center;
  font-size: 14px;
  line-height: 28px;
}

.left-hand-TextDom, .Courses-head {
  background-color: #f2f6f7;
}

.Courses-leftHand {
  background-color: #f2f6f7;
  font-size: 12px;
}

.Courses-leftHand .left-hand-index {
  color: #9c9c9c;
  margin-bottom: 4px !important;
}

.Courses-leftHand p {
  text-align: center;
  font-weight: 900;
}

.Courses-leftHand > div {
  padding-top: 5px;
  border-bottom: 1px dashed rgb(219, 219, 219);
}

.Courses-leftHand > div:last-child {
  border-bottom: none !important;
}

.left-hand-TextDom, .Courses-head {
  border-bottom: 1px solid rgba(0, 0, 0, 0.1) !important;
}

.Courses-content > ul {
  border-bottom: 1px dashed rgb(219, 219, 219);
  box-sizing: border-box;
}

.Courses-content > ul:last-child {
  border-bottom: none !important;
}

.highlight-week {
  color: #02a9f5 !important;
}

.Courses-content li {
  text-align: center;
  color: #fff;
  font-size: 14px;
  line-height: 50px;
}

.stage_1, .left-hand-1 {
  /*background-color: #FF6666;*/
}

.stage_2, .left-hand-2 {
  /*background-color: #3399CC;*/
}

.stage_3, .left-hand-3 {
  /*background-color: #66CCCC;*/
}

.Courses-leftHand {
  border-right: 1px solid #e0e0e0;
  color: #303133;
}

.Courses-leftHand > div {
  writing-mode: vertical-lr;
  text-align: center;
  line-height: 50px;
  font-size: 16px;
  letter-spacing: 10px;
}
</style>
